<template>
  <div class="home-container">
    <a-layout>
      <a-layout-header>
        <div class="header-content">
          <div class="logo">
            Easy Admin
          </div>
          <div class="header-right">
            <a-space :size="16">
              <!-- 切换角色 -->
              <a-tooltip content="切换角色">
                <a-button type="text" @click="handleRoleSwitch">
                  <template #icon><icon-user /></template>
                </a-button>
              </a-tooltip>
              
              <!-- 用户中心 -->
              <a-tooltip content="用户中心">
                <a-button type="text" @click="handleUserCenter">
                  <template #icon><icon-user /></template>
                </a-button>
              </a-tooltip>
              
              <!-- 用户设置 -->
              <a-tooltip content="用户设置">
                <a-button type="text" @click="handleUserSettings">
                  <template #icon><icon-settings /></template>
                </a-button>
              </a-tooltip>
              
              <!-- 用户下拉菜单 -->
              <a-dropdown @select="handleUserAction">
                <a-button type="text">
                  {{ userStore.getUserInfo.username || '用户' }}
                  <icon-down />
                </a-button>
                <template #content>
                  <a-doption value="profile">个人信息</a-doption>
                  <a-doption value="logout">退出登录</a-doption>
                </template>
              </a-dropdown>
            </a-space>
          </div>
        </div>
      </a-layout-header>
      <a-layout>
        <a-layout-sider collapsible>
          <a-menu
            :default-selected-keys="[currentMenuKey]"
            :default-open-keys="openKeys"
            :style="{ width: '100%' }"
            :auto-open="true"
            @menu-item-click="handleMenuClick"
          >
            <template v-for="menu in menuList" :key="menu.id">
              <!-- 目录类型菜单 -->
              <a-sub-menu  v-if="menu.menuType === 'M' && menu.children && menu.children.length > 0" :key="menu.id">
                <template #icon>
                  <component :is="getIconComponent(menu.icon)" />
                </template>
                <template #title>{{ menu.menuName }}</template>
                <a-menu-item v-for="child in menu.children" :key="child.id" :data-path="child.path">
                  <template #icon>
                    <component :is="getIconComponent(child.icon)" />
                  </template>
                  {{ child.menuName }}
                </a-menu-item>
              </a-sub-menu>
              <!-- 菜单类型 -->
              <a-menu-item v-else-if="menu.menuType === 'C'" :key="menu.id" :data-path="menu.path">
                <template #icon>
                  <component :is="getIconComponent(menu.icon)" />
                </template>
                {{ menu.menuName }}
              </a-menu-item>
            </template>
          </a-menu>
        </a-layout-sider>
        <a-layout-content>
          <router-view></router-view>
        </a-layout-content>
      </a-layout>
    </a-layout>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useUserStore } from '../stores/user'
import { useRouter, useRoute } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import request from '../api/request'
import {
  IconDashboard,
  IconUser,
  IconSettings,
  IconDown,
  IconMenu,
  IconHome,
  IconList,
  IconTool
} from '@arco-design/web-vue/es/icon'

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()

const menuList = ref([])
const currentMenuKey = ref('')
const openKeys = ref([])

// 获取用户菜单
const getUserMenus = async () => {
  try {
    const res = await request.get('/api/SysMenu/tree')
    menuList.value = res.data || []
  } catch (error) {
    console.error('获取菜单失败:', error)
    Message.error('获取菜单失败')
  }
}

// 获取图标组件
const getIconComponent = (iconName) => {
  const iconMap = {
    'dashboard': IconDashboard,
    'user': IconUser,
    'system': IconSettings,
    'menu': IconMenu,
    'home': IconHome,
    'list': IconList,
    'tool': IconTool,
    'peoples': IconUser,
    'tree-table': IconList
  }
  return iconMap[iconName] || IconMenu
}

// 根据路径查找菜单ID和父菜单ID
const findMenuByPath = (menus, path, parentId = null) => {
  for (const menu of menus) {
    if (menu.path === path) {
      return {
        menuId: menu.id.toString(),
        parentId: parentId ? parentId.toString() : null
      }
    }
    if (menu.children && menu.children.length > 0) {
      const found = findMenuByPath(menu.children, path, menu.id)
      if (found) return found
    }
  }
  return { menuId: '', parentId: null }
}

// 设置当前选中的菜单
const setCurrentMenu = () => {
  const currentPath = route.path
  const result = findMenuByPath(menuList.value, currentPath)
  currentMenuKey.value = result.menuId
  
  // 设置需要展开的父菜单
  if (result.parentId) {
    openKeys.value = [result.parentId]
  } else {
    openKeys.value = []
  }
}

// 监听路由变化
watch(() => route.path, () => {
  setCurrentMenu()
}, { immediate: false })

onMounted(async () => {
  await getUserMenus()
  setCurrentMenu()
})

const handleUserAction = (key) => {
  switch (key) {
    case 'profile':
      router.push('/profile')
      break
    case 'logout':
      userStore.logout()
      Message.success('已退出登录')
      router.push('/login')
      break
  }
}

// 切换角色
const handleRoleSwitch = () => {
  Message.info('切换角色功能')
  // TODO: 实现角色切换逻辑
}

// 用户中心
const handleUserCenter = () => {
  router.push('/user-center')
}

// 用户设置
const handleUserSettings = () => {
  router.push('/user-settings')
}

const handleMenuClick = (key) => {
  console.log('菜单点击 - key:', key)
  console.log('菜单列表:', menuList.value)
  
  // 查找菜单项
  const findMenuById = (menus, id) => {
    for (const menu of menus) {
      if (menu.id === id) {
        return menu
      }
      if (menu.children && menu.children.length > 0) {
        const found = findMenuById(menu.children, id)
        if (found) return found
      }
    }
    return null
  }
  
  const menu = findMenuById(menuList.value, key)
  console.log('找到的菜单:', menu)
  
  if (menu && menu.path) {
    console.log('准备跳转到:', menu.path)
    currentMenuKey.value = key
    
    // 处理路径格式：后端返回的是绝对路径（如/system/menu），前端路由需要相对路径（如system/menu）
    let targetPath = menu.path
    if (targetPath.startsWith('/')) {
      targetPath = targetPath.substring(1) // 移除开头的斜杠
    }
    
    console.log('实际跳转路径:', targetPath)
    router.push('/' + targetPath)
  } else {
    console.warn('菜单未找到或路径为空:', { menu, key })
    Message.warning('菜单配置错误，无法跳转')
  }
}
</script>

<style scoped>
.home-container {
  height: 100vh;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #fff;
}

.logo {
  font-size: 20px;
  font-weight: bold;
}

:deep(.arco-layout-header) {
  background-color: rgb(var(--primary-6));
  padding: 0 20px;
}

:deep(.arco-layout-content) {
  padding: 20px;
  background-color: var(--color-neutral-2);
}

:deep(.arco-layout-sider) {
  background-color: var(--color-bg-2);
}

.header-right {
  display: flex;
  align-items: center;
}

.header-right .arco-btn-text {
  color: rgba(255, 255, 255, 0.8);
  transition: color 0.2s;
}

.header-right .arco-btn-text:hover {
  color: #fff;
  background-color: rgba(255, 255, 255, 0.1);
}
</style>